﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using WeatherSystem.Application.Model;

namespace WeatherSystem.Net
{
    class UdpServer
    {
        private UdpClient server;
        public IPAddress Address { get; private set; }
        public int Port { get; private set; }
        public UdpServer(int port)
        {
            Address = IPAddress.Any;
            Port = port;
            server = new UdpClient(new IPEndPoint(Address, Port));
        }

        public void Start()
        {
            server.BeginReceive(RecieveData, null);
        }

        private void RecieveData(IAsyncResult ar)
        {
            var data_model = new DataModel();
            server.BeginReceive(RecieveData, null);
            IPEndPoint remote = null;
            var byte_data = server.EndReceive(ar, ref remote);
            MemoryStream ms = new MemoryStream(byte_data);
            StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("GB2312"));
            var data = sr.ReadToEnd();
            sr.Close();
            if (data.IndexOf("$WD") == -1) return;
            try
            {
                var data_str = data.Split(',');
                var sn = data_str[1];
                var temp = data_str[2];
                var wet = data_str[3];
                var press = data_str[4];
                var longitude = data_str[5];
                var latitude = data_str[6];
                var altitude = data_str[7];
                Program.Log("接收到来自{0}的数据:{1}", sn.Substring(0, 4) + "~", data);
                data_model.Insert(new Dictionary<string, object>
                {
                    { "device", sn },
                    { "time", Data.Convert.ToTimeStamp(DateTime.Now) },
                    { "longitude", longitude },
                    { "latitude", latitude },
                    { "altitude", altitude },
                    { "temp", temp },
                    { "wet", wet },
                    { "press", press }
                });
            }
            catch(IndexOutOfRangeException)
            {
                Program.Warning("接收到了数据，但数据帧格式有误.");
                Program.Warning("错误数据:{0}", data);
            }
            catch
            {
                Program.Error("数据帧处理时发生未知异常.");
            }
        }
    }
}
